<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use App\Models\Recharge;
use App\Models\Property;
use App\Models\Currency;
use DB;

/**
 * 取消过期订单
 */
class CancelOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cancel:order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //获取所有未付款，已超时的订单
        $orders = Recharge::where('status', 1)->get();

        dump(collect($orders)->count());

        $cid = Currency::where('name_en', 'USDT')->value('id');

        foreach($orders as $order) {
            //判断过期时间
            $createTime = strtotime($order->created_at);

            //超过60分钟
            if (($createTime + 3600) < time()) {
                //开启事务
                DB::beginTransaction();
                //如果有取消订单的其他限制，在上面分别做判断
                $order->update(['status' => 4]);
                //如果是用户卖出，解冻用户资产
                if ($order->type == 2) {
                    $property = Property::where(['uid' => $order->uid, 'cid' => $cid])->first();
                    $property->increment('balance', $order->num);
                    $property->decrement('blocked', $order->num);
                }
                DB::commit();
            }

        }
    }
}
